import { BASE_API } from '@/utils/config'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message } from '@/utils/wxUtil'
import { tansParams } from '@/utils/util'
import store from '../store/index'

let timeout = 10000
const baseUrl = BASE_API
// 默认参数
const defaultOptions = {
  needLoading: true,
  needMsg: true
}
const request = config => {
	// 处理config 参数 赋值问题
	config.config = Object.assign({}, defaultOptions, config.config)
  config.header = config.header || {}
  config.header['content-type'] = 'application/json'
  config.header['Authorization'] = uni.getStorageSync('App-Token')
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.url = url
  }
  return new Promise((resolve, reject) => {
		if (config.config.needLoading) {
			Message.loading.show('請稍後');
		}
    uni.request({
			url: baseUrl + config.url,
			method: config.method,
			timeout: config.timeout || timeout,
			data: config.data,
			header: config.header,
			success: (res) => {
				// 是否存在状态码 code
				if (res.data.hasOwnProperty('code')) {
					res.data.code = Number(res.data.code)
				}
				if (res.data.code == 200) {
					// 如返回新的access_token 则保存
					if (res.header.Authorization) {
						setToken(res.header.Authorization)
					}
					resolve(res.data);
				} else {
					reject(res.data);
				}
			},
			fail: (err) => {
				console.log('request fail', res)
				reject(res);
			},
			complete: (res) => {
				if (config.config.needLoading) {
					Message.loading.hide()
				}
				if (res.data) {
					// 非 500 404
					if (config.config.needMsg && res.data.hasOwnProperty('code') && res.data.code != 200) {
						Message.warns(res.data.msg)
					}
					// 401 尚未登录
					if ([401, 502].includes(res.data.code)) {
						Message.warns(res.data.msg)
						// 清除本地所有缓存，重新登录
						removeToken()
						store.commit('CHANGE_SETTING', {
							isLogin: false
						})
					}
				} else {
					// 500
					if (res.statusCode == 500) {
						Message.warns('500 Internal Server Error')
					}
					// 请求超时
					if (res.errMsg.indexOf('timeout') >= 0) {
						Message.warns('請求超時，請稍後重試')
					}
				}
			}
		})
  })
}

export default request
